<template>
  <el-dialog
    v-model="visible"
    title="导入照片"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <div class="import-dialog">
      <div class="import-section">
        <div class="section-title">选择文件夹</div>
        <div class="folder-selector">
          <el-input
            v-model="selectedFolderPath"
            placeholder="请选择要导入的文件夹"
            readonly
          >
            <template #append>
              <el-button @click="selectFolder">浏览</el-button>
            </template>
          </el-input>
        </div>
        <div class="folder-options">
          <el-checkbox v-model="includeSubfolders">包含子文件夹</el-checkbox>
          <el-checkbox v-model="skipDuplicates">跳过重复文件</el-checkbox>
        </div>
      </div>
      
      <div class="import-section">
        <div class="section-title">导入选项</div>
        <div class="import-options">
          <el-form label-width="120px">
            <el-form-item label="创建缩略图">
              <el-switch v-model="createThumbnails" />
            </el-form-item>
            <el-form-item label="提取元数据">
              <el-switch v-model="extractMetadata" />
            </el-form-item>
            <el-form-item label="文件类型">
              <el-checkbox-group v-model="selectedFileTypes">
                <el-checkbox label="jpg">JPEG</el-checkbox>
                <el-checkbox label="png">PNG</el-checkbox>
                <el-checkbox label="heic">HEIC</el-checkbox>
                <el-checkbox label="raw">RAW</el-checkbox>
                <el-checkbox label="gif">GIF</el-checkbox>
                <el-checkbox label="bmp">BMP</el-checkbox>
                <el-checkbox label="tiff">TIFF</el-checkbox>
                <el-checkbox label="webp">WebP</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <div v-if="importStatus === 'importing'" class="import-section">
        <div class="section-title">导入进度</div>
        <div class="import-progress">
          <el-progress
            :percentage="importProgress.percentage"
            :status="importProgress.status"
          />
          <div class="progress-info">
            <div>已处理: {{ importProgress.processed }} / {{ importProgress.total }}</div>
            <div>成功: {{ importProgress.success }}</div>
            <div>失败: {{ importProgress.failed }}</div>
            <div>跳过: {{ importProgress.skipped }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="importStatus === 'importing'"
          :disabled="!canStartImport"
          @click="startImport"
        >
          {{ importStatus === 'importing' ? '导入中...' : '开始导入' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElDialog, ElInput, ElButton, ElCheckbox, ElCheckboxGroup, ElSwitch, ElForm, ElFormItem, ElProgress } from 'element-plus';

interface Props {
  modelValue: boolean;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'import', options: ImportOptions): void;
}

interface ImportOptions {
  folderPath: string;
  includeSubfolders: boolean;
  skipDuplicates: boolean;
  createThumbnails: boolean;
  extractMetadata: boolean;
  fileTypes: string[];
}

interface ImportProgress {
  percentage: number;
  processed: number;
  total: number;
  success: number;
  failed: number;
  skipped: number;
  status: 'success' | 'exception' | 'warning' | undefined;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 对话框可见性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

// 导入选项
const selectedFolderPath = ref('');
const includeSubfolders = ref(true);
const skipDuplicates = ref(true);
const createThumbnails = ref(true);
const extractMetadata = ref(true);
const selectedFileTypes = ref(['jpg', 'png', 'heic', 'raw']);

// 导入状态
const importStatus = ref<'idle' | 'importing' | 'completed' | 'error'>('idle');
const importProgress = ref<ImportProgress>({
  percentage: 0,
  processed: 0,
  total: 0,
  success: 0,
  failed: 0,
  skipped: 0,
  status: undefined
});

// 是否可以开始导入
const canStartImport = computed(() => {
  return selectedFolderPath.value.trim() !== '' && 
         selectedFileTypes.value.length > 0 && 
         importStatus.value !== 'importing';
});

// 选择文件夹
const selectFolder = async () => {
  try {
    // 使用 Electron 的文件夹选择对话框
    const { dialog } = await import('electron');
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory'],
      title: '选择要导入的文件夹'
    });
    
    if (!result.canceled && result.filePaths.length > 0) {
      selectedFolderPath.value = result.filePaths[0];
    }
  } catch (error) {
    console.error('选择文件夹失败:', error);
  }
};

// 开始导入
const startImport = () => {
  if (!canStartImport.value) return;
  
  importStatus.value = 'importing';
  importProgress.value = {
    percentage: 0,
    processed: 0,
    total: 0,
    success: 0,
    failed: 0,
    skipped: 0,
    status: undefined
  };
  
  const options: ImportOptions = {
    folderPath: selectedFolderPath.value,
    includeSubfolders: includeSubfolders.value,
    skipDuplicates: skipDuplicates.value,
    createThumbnails: createThumbnails.value,
    extractMetadata: extractMetadata.value,
    fileTypes: selectedFileTypes.value
  };
  
  emit('import', options);
};

// 更新导入进度
const updateProgress = (progress: Partial<ImportProgress>) => {
  importProgress.value = { ...importProgress.value, ...progress };
};

// 完成导入
const completeImport = (status: 'completed' | 'error') => {
  importStatus.value = status;
  if (status === 'completed') {
    importProgress.value.percentage = 100;
    importProgress.value.status = 'success';
  } else {
    importProgress.value.status = 'exception';
  }
};

// 关闭对话框
const handleClose = () => {
  if (importStatus.value === 'importing') {
    // 导入中不允许关闭
    return;
  }
  
  visible.value = false;
  
  // 重置状态
  if (importStatus.value === 'completed') {
    selectedFolderPath.value = '';
    importStatus.value = 'idle';
    importProgress.value = {
      percentage: 0,
      processed: 0,
      total: 0,
      success: 0,
      failed: 0,
      skipped: 0,
      status: undefined
    };
  }
};

// 暴露方法给父组件
defineExpose({
  updateProgress,
  completeImport
});
</script>

<style scoped lang="scss">
.import-dialog {
  .import-section {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .section-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 12px;
      color: var(--el-text-color-primary);
    }
    
    .folder-selector {
      margin-bottom: 12px;
    }
    
    .folder-options {
      display: flex;
      gap: 16px;
    }
    
    .import-options {
      .el-form-item {
        margin-bottom: 12px;
      }
    }
    
    .import-progress {
      .progress-info {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 8px;
        margin-top: 12px;
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>